package com.seezoon.infrastructure.tcp.session;

import io.netty.util.AttributeKey;
import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicInteger;

public class ClientSession {

    public final static AttributeKey<ClientSession> key = AttributeKey.valueOf("clientSession");
    /**
     * 终端序列号
     */
    private final String clientId;
    private final AtomicInteger sequence = new AtomicInteger(0);
    private final LocalDateTime createTime = LocalDateTime.now();
    private LocalDateTime lastAccessTime = LocalDateTime.now();

    public ClientSession(String clientId) {
        this.clientId = clientId;
    }

    public String getClientId() {
        lastAccessTime = LocalDateTime.now();
        return clientId;
    }

    public int nextSequence() {
        lastAccessTime = LocalDateTime.now();
        // 无符号short 最大值后，从0 开始
        return sequence.getAndUpdate(current ->
                (current >= 65535) ? 0 : current + 1
        );
    }
}
